﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
using System.IO;
using System.Threading;

namespace TranAPI
{
    public partial class Form1 : Form
    {
        Thread th = null;
        public Form1()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            th = new Thread(new ThreadStart(exe));
            th.Start();
        }
        private void exe() {
            this.button1.Enabled = false;
            Common.saveSystem(this.textBox2.Text, this.textBox1.Text);

            /*
            string templateFile = @"D:\Word模板.doc";
            //生成的具有模板样式的新文件
            string fileName = @"D:\导出后的Word文件" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".doc";
            ExportWord(templateFile, fileName);
            */

            IEnumerable<string> strs = System.IO.File.ReadLines(this.textBox1.Text);


            Word.Application app = null;
            Word.Document doc = null;
            object EndOfDoc = "\\endofdoc";
            try
            {

                int rows = 1;
                int cols = 2;//表格列数
                object oMissing = System.Reflection.Missing.Value;
                app = new Word.Application();//创建word应用程序
                doc = app.Documents.Add();//添加一个word文档

                //输出大标题加粗加大字号水平居中
                app.Selection.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

                //换行添加表格
                object line = Word.WdUnits.wdLine;
                app.Selection.MoveDown(ref line, oMissing, oMissing);
                app.Selection.TypeParagraph();//换行
                bool begin = false;
                List<Dict> dict = new List<Dict>();
                int count = 0;
                object unite = Word.WdUnits.wdStory;
                var title = "";
                foreach (string str in strs)
                {
                    if (str.Contains("#region"))
                    {
                        begin = true;
                        dict = new List<Dict>();
                        count++;
                        title = (count + "." + str.Replace("#region", "").Trim());
                        app.Selection.EndKey(ref unite, ref oMissing);//将光标移到文本末尾
                        app.Selection.ParagraphFormat.FirstLineIndent = 0;//取消首行缩进的长度
                        doc.Paragraphs.Last.Range.Font.Color = Word.WdColor.wdColorBlack;
                        doc.Paragraphs.Last.Range.Font.Bold = 1;
                        doc.Paragraphs.Last.Range.Text = title + "\n";
                    }
                    if (str.Contains("hs.Add"))
                    {
                        var str0 = str.Split('"');
                        app.Selection.EndKey(ref unite, ref oMissing);//将光标移到文本末尾
                        doc.Paragraphs.Last.Range.Font.Size = 12;
                        doc.Paragraphs.Last.Range.Font.Bold = 0;
                        doc.Paragraphs.Last.Range.Font.Color = Word.WdColor.wdColorBlue;
                        doc.Paragraphs.Last.Range.Font.Name = "宋体";
                        doc.Paragraphs.Last.Range.Text = "act：" + str0[1] + "\n";
                    }
                    if (begin && str.Contains("JobRequest"))
                    {
                        Dict d = new Dict();
                        var str1 = str.Split('"');
                        var str2 = str.Split('/');
                        if (str1.Length >= 2)
                        {
                            d.Name = str1[1];
                        }
                        if (str2.Length >= 3)
                        {
                            d.Value = str2[2];
                        }
                        dict.Add(d);
                    }
                    if (str.Contains("#endregion"))
                    {

                        foreach (var i in dict)
                        {

                            var strContent = i.Name + "：" + i.Value + "\n"; //
                            app.Selection.EndKey(ref unite, ref oMissing);//这一句不加，有时候好像也不出问题，不过还是加了安全    
                            doc.Paragraphs.Last.Range.Font.Size = 12;
                            doc.Paragraphs.Last.Range.Font.Bold = 0;
                            doc.Paragraphs.Last.Range.Font.Color = Word.WdColor.wdColorBlack;
                            doc.Paragraphs.Last.Range.Font.Name = "宋体";
                            doc.Paragraphs.Last.Range.Text = strContent;
                        }
                        line = Word.WdUnits.wdLine;
                        app.Selection.MoveDown(ref line, oMissing, oMissing);
                        app.Selection.TypeParagraph();//换行
                        begin = false;

                    }
                }



                //导出到文件
                string newFile = this.textBox2.Text + "API接口.doc";
                string physicNewFile = ("c:/" + newFile);
                doc.SaveAs(physicNewFile,
                oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();//关闭文档
                    this.button1.Enabled = true;
                    MessageBoxButtons messButton = MessageBoxButtons.YesNo;
                    DialogResult dr = MessageBox.Show("生成成功，是否打开文件夹？", "提示", messButton);
                    if (dr == DialogResult.Yes)//如果点击“确定”按钮
                    {
                        System.Diagnostics.Process.Start(@"C:\");
                    }
                }
                if (app != null)
                {
                    app.Quit();//退出应用程序
                }
                th.Abort();
            }
            
        }
        private void button2_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.ShowDialog();
            this.textBox1.Text = this.openFileDialog1.FileName;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.textBox2.Text = Common.GetConfig("Name");
            this.textBox1.Text = Common.GetConfig("Path");
        }



        /*
        /// <summary>
        /// 调用模板生成word
        /// </summary>
        /// <param name="templateFile">模板文件</param>
        /// <param name="fileName">生成的具有模板样式的新文件</param>
        public void ExportWord(string templateFile, string fileName)
        {
            try
            {
                //生成word程序对象
                Word.Application app = new Word.Application();

                //模板文件
                string TemplateFile = templateFile;
                //生成的具有模板样式的新文件
                string FileName = fileName;

                //模板文件拷贝到新文件
                File.Copy(TemplateFile, FileName);
                //生成documnet对象
                Word.Document doc = new Word.Document();
                object Obj_FileName = FileName;
                object Visible = false;
                object ReadOnly = false;
                object missing = System.Reflection.Missing.Value;

                //打开文件
                doc = app.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                    ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref Visible,
                    ref missing, ref missing, ref missing,
                    ref missing);
                doc.Activate();

                int WordNum = 4;//书签个数
                //将光标转到模板中定义的书签的位置，插入所需要添加的内容，循环次数与书签个数相符
                for (int WordIndex = 1; WordIndex <= WordNum; WordIndex++)
                {
                    object WordMarkName = "书签名称" + WordIndex.ToString();//word模板中的书签名称
                    object what = Word.WdGoToItem.wdGoToBookmark;
                    doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref WordMarkName);//光标转到书签的位置
                    doc.ActiveWindow.Selection.TypeText("插入的内容" + WordIndex.ToString());//插入的内容，插入位置是word模板中书签定位的位置
                    doc.ActiveWindow.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//设置当前定位书签位置插入内容的格式
                    //doc.ActiveWindow.Selection.TypeParagraph();//回车换行
                }

                //输出完毕后关闭doc对象
                object IsSave = true;
                doc.Close(ref IsSave, ref missing, ref missing);

                MessageBox.Show("生成“" + FileName + "”成功!");
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.ToString());
                return;
            }
        }
        */
    }
    class Dict
    {
        public string Name = "";
        public string Value = "";
    }
}
